package top.wuyang.study.java24.servlet.software;

import top.wuyang.study.java24.dao.TbSoftwareDAO;
import top.wuyang.study.java24.dao.TbSoftwareTypeDAO;
import top.wuyang.study.java24.entity.Result;
import top.wuyang.study.java24.entity.TbSoftware;
import top.wuyang.study.java24.entity.TbSoftwareType;
import top.wuyang.study.java24.util.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "softwareInsertServlet", urlPatterns = "/software/insert.action")
public class InsertServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        resp.setContentType("application/json");
        try {
            Integer type_id = Integer.parseInt(req.getParameter("type_id"));
            String software_name = req.getParameter("software_name");
            String vendor = req.getParameter("vendor");
            String description = req.getParameter("description");
            // 验证是否已经存在该类型
            TbSoftwareType softwareType = TbSoftwareTypeDAO.queryById(type_id);
            if (softwareType == null) {
                Result<String> result = Result.fail("类型不存在", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            TbSoftware software = new TbSoftware();
            software.setType_id(type_id);
            software.setSoftware_name(software_name);
            software.setDescription(description);
            software.setVendor(vendor);
            int i = TbSoftwareDAO.insert(software);
            if (i == 1) {
                Result<String> result = Result.success("添加成功", null);
                writer.println(JsonUtils.stringify(result));
            } else {
                Result<String> result = Result.fail("添加失败", null);
                writer.println(JsonUtils.stringify(result));
            }


        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = Result.fail("添加发生错误", null);
            writer.println(JsonUtils.stringify(result));
        }
    }


}
